package org.like.sso.client.sso.client;

import java.io.IOException;
import java.io.UnsupportedEncodingException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * <p>
 * Title: 单点登陆客户端的filter
 * </p>
 * <p>
 * Description: 单点登陆客户端的filter,用来拦截浏览器对接入系统的请求
 * </p>
 * <p>
 * 2010-7-13 下午10:43:54
 * </p>
 * 
 * @author 陈辉
 * @version 1.0
 * 
 */
public class SSOFilter implements Filter {

	private String encoding = "";

	public void destroy() {

	}

	public void doFilter(ServletRequest arg0, ServletResponse arg1,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) arg0;
		HttpServletResponse response = (HttpServletResponse) arg1;
		setEncoding(request, response);
		String token = request.getParameter(SSOConstants.SSO_TOKEN);
		String requestPage = request.getRequestURI();
		String path = request.getContextPath();
		String basePath = request.getScheme() + "://" + request.getServerName()
				+ ":" + request.getServerPort() + path + "/";
		String sessionToken = (String) request.getSession().getAttribute(
				SSOConstants.SSO_TOKEN);
		
		//为空则证明这是一个新的请求，需要进行认证，
		//不为空则认为是已经存在的会话的请求，直接放过去，不做验证
		if (sessionToken == null) {

			// 检查单前url是否需要拦截
			boolean checkURL = ClientUtil.checkURL(requestPage);
			// 如果需要拦截
			if (checkURL) {
				// 检查现在用户是否在线，当前token是否有效
				String onLineUser = ClientUtil.checkOnLine(request);

				// 如果不在线
				if (onLineUser == null || "".equals(onLineUser)) {
					response.sendRedirect(basePath + SSOConstants.AC_FAILURE
							+ "?" + SSOConstants.REQUEST_ATTRIBUTE_MESSAGE_KEY
							+ "=" + SSOConstants.USER_UNLOGIN);
				} else if (onLineUser
						.equals(SSOConstants.UNAUTHORIZED_IP_ACCESS)
						|| onLineUser.equals(SSOConstants.USER_UNLOGIN)
						|| onLineUser.equals(SSOConstants.SYS_ERROR)
						|| onLineUser.equals(SSOConstants.SYS_ERROR_DB)
						|| onLineUser.equals(SSOConstants.SYS_ERROR_NO_PARAMETER)) {// 如果返回的是错误码，就跳转到错误页面
					response.sendRedirect(basePath + SSOConstants.AC_FAILURE
							+ "?" + SSOConstants.REQUEST_ATTRIBUTE_MESSAGE_KEY
							+ "=" + onLineUser);
				} else {// 如果再线,把token和用户id保存到session中
					request.getSession().setAttribute(SSOConstants.SSO_TOKEN,
							token);
					request.getSession().setAttribute(SSOConstants.SSO_ACCOUNT,
							onLineUser);
				}
			}
		}

		chain.doFilter(arg0, arg1);

	}

	public void init(FilterConfig arg0) throws ServletException {
		encoding = arg0.getInitParameter("encoding");

		ClientUtil.initBaseConfig("/baseconfig.properties");
		ClientUtil.initAppConfig("/appconfig.properties");

	}

	private void setEncoding(ServletRequest request, ServletResponse response)
			throws UnsupportedEncodingException {
		HttpServletRequest Request = (HttpServletRequest) request;

		if (encoding != null && !"".equals(encoding)) {
			Request.setCharacterEncoding(encoding);
		}
		if (encoding != null && !encoding.equals(""))
			Request.setCharacterEncoding(encoding);
	}

}
